import asyncio
from typing import Optional

from config.logging_config import get_logger

logger = get_logger(__name__)


def cleanup_event_loop(loop: Optional[asyncio.AbstractEventLoop] = None):
    """清理事件循环和相关资源"""
    try:
        if loop is None:
            try:
                loop = asyncio.get_running_loop()
            except RuntimeError:
                try:
                    loop = asyncio.get_event_loop()
                except RuntimeError:
                    return

        if loop and not loop.is_closed():
            # 取消所有未完成的任务
            pending_tasks = [task for task in asyncio.all_tasks(loop) if not task.done()]

            if pending_tasks:
                logger.info(f"正在取消 {len(pending_tasks)} 个未完成的异步任务...")
                for task in pending_tasks:
                    task.cancel()

                # 等待任务完成取消
                if loop.is_running():
                    # 如果事件循环正在运行，不能在这里等待
                    pass
                else:
                    # 如果事件循环没有运行，可以运行它来完成取消
                    try:
                        loop.run_until_complete(
                            asyncio.gather(*pending_tasks, return_exceptions=True)
                        )
                    except Exception as e:
                        logger.warning(f"取消异步任务时出现异常: {str(e)}")

            # 关闭事件循环
            if not loop.is_closed():
                loop.close()
                logger.info("事件循环已关闭")

    except Exception as e:
        logger.warning(f"清理事件循环时出现异常: {str(e)}")


def setup_cleanup_on_exit():
    """设置程序退出时的清理操作"""
    import atexit

    def cleanup():
        # 清理事件循环
        cleanup_event_loop()

        # 强制垃圾回收
        import gc
        gc.collect()

    atexit.register(cleanup)


# 自动设置
if __name__ != "__main__":
    setup_cleanup_on_exit()
